<template>
  <div class="child-list">
    <h2>孩子管理</h2>
    
    <!-- 添加孩子表单 -->
    <div class="child-form" v-if="showAddForm">
      <h3>添加新孩子</h3>
      <form @submit.prevent="createChild">
        <div class="form-group">
          <label>姓名</label>
          <input v-model="newChild.name" placeholder="请输入孩子姓名" required>
        </div>
        <div class="form-group">
          <label>年龄</label>
          <input type="number" v-model="newChild.age" placeholder="请输入年龄" required min="1" max="18">
        </div>
        <div class="form-group">
          <label>年级</label>
          <select v-model="newChild.grade" required>
            <option value="">请选择年级</option>
            <option value="幼儿园">幼儿园</option>
            <option value="一年级">一年级</option>
            <option value="二年级">二年级</option>
            <option value="三年级">三年级</option>
            <option value="四年级">四年级</option>
            <option value="五年级">五年级</option>
            <option value="六年级">六年级</option>
            <option value="初一">初一</option>
            <option value="初二">初二</option>
            <option value="初三">初三</option>
          </select>
        </div>
        <div class="form-buttons">
          <button type="submit" class="primary">添加</button>
          <button type="button" @click="showAddForm = false" class="secondary">取消</button>
        </div>
      </form>
    </div>

    <!-- 添加孩子按钮 -->
    <button v-if="!showAddForm" @click="showAddForm = true" class="add-button">
      <span class="plus">+</span> 添加孩子
    </button>

    <!-- 孩子列表 -->
    <div class="children">
      <div v-for="child in children" :key="child.id" class="child-item">
        <div class="child-info">
          <h3>{{ child.name }}</h3>
          <p>年龄: {{ child.age }}岁</p>
          <p>年级: {{ child.grade }}</p>
          <p>积分: {{ child.points }}</p>
        </div>
        <div class="child-actions">
          <button @click="viewHabits(child.id)">习惯管理</button>
          <button @click="viewCalendar(child.id)">打卡日历</button>
          <button @click="viewStatistics(child.id)">数据统计</button>
        </div>
      </div>
      <div v-if="children.length === 0 && !showAddForm" class="no-children">
        还没有添加孩子，点击上方按钮添加
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ChildList',
  data() {
    return {
      children: [],
      showAddForm: false,
      newChild: {
        name: '',
        age: '',
        grade: '',
        parent_id: null
      }
    }
  },
  methods: {
    async fetchChildren() {
      try {
        const token = localStorage.getItem('token')
        const response = await axios.get('/api/children', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        this.children = response.data
      } catch (error) {
        console.error('获取孩子列表失败:', error)
        if (error.response?.status === 401) {
          // Token 失效，重新登录
          localStorage.removeItem('token')
          localStorage.removeItem('userId')
          localStorage.removeItem('userRole')
          this.$router.push('/login')
        } else {
          alert('获取孩子列表失败: ' + (error.response?.data?.error || error.message))
        }
      }
    },
    async createChild() {
      try {
        const token = localStorage.getItem('token')
        const userId = localStorage.getItem('userId')
        
        const childData = {
          name: this.newChild.name,
          age: parseInt(this.newChild.age),
          grade: this.newChild.grade,
          parent_id: parseInt(userId)
        }

        await axios.post('/api/children', childData, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        await this.fetchChildren()
        this.showAddForm = false
        this.resetForm()
      } catch (error) {
        console.error('添加孩子失败:', error)
        alert('添加孩子失败: ' + (error.response?.data?.error || error.message))
      }
    },
    resetForm() {
      this.newChild = {
        name: '',
        age: '',
        grade: ''
      }
    },
    viewHabits(childId) {
      this.$router.push(`/habits/${childId}`)
    },
    viewCalendar(childId) {
      this.$router.push(`/calendar/${childId}`)
    },
    viewStatistics(childId) {
      this.$router.push(`/statistics/${childId}`)
    }
  },
  mounted() {
    this.fetchChildren()
  }
}
</script>

<style scoped>
.child-list {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.child-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button.primary {
  background-color: #42b983;
  color: white;
}

button.secondary {
  background-color: #666;
  color: white;
}

.add-button {
  width: 100%;
  padding: 15px;
  margin-bottom: 20px;
  background-color: #f5f5f5;
  border: 2px dashed #ddd;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
}

.plus {
  font-size: 20px;
  margin-right: 8px;
}

.children {
  display: grid;
  gap: 20px;
}

.child-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.child-info h3 {
  margin: 0 0 10px 0;
  color: #42b983;
}

.child-info p {
  margin: 5px 0;
  color: #666;
}

.child-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.child-actions button {
  flex: 1;
  background-color: #42b983;
  color: white;
}

.no-children {
  text-align: center;
  color: #666;
  padding: 40px;
  background: #f5f5f5;
  border-radius: 8px;
}
</style> 